package com.ijava.base.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ijava.base.domain.DictionaryDefine;
import com.ijava.base.domain.Menu;
import com.ijava.base.domain.Model;
import com.ijava.base.domain.Role;
import com.ijava.base.domain.User;
import com.ijava.base.service.MenuService;
import com.ijava.base.service.ModelService;
import com.ijava.util.DTreeBean;
import com.ijava.util.SystemConfig;

@Controller
@RequestMapping("/admin/menu.do")
@SessionAttributes("list")
public class MenuController {
	private static final Logger logger = LoggerFactory.getLogger(MenuController.class);
	@Autowired
	private ModelService modelService;
	@Autowired
	private MenuService service;
	
	@RequestMapping(params = "action=index")
	public String index(ModelMap modelMap, HttpSession session)
			throws Exception {
		try {
			String modelId = SystemConfig.getProperty("MODEL.ID");
			Model model = modelService.get(modelId);
			if(null == model){
				User loginUser = (User)session.getAttribute("loginUser");
				String modelParentId = SystemConfig.getProperty("MODEL.PID");
				String modelCode = SystemConfig.getProperty("MODEL.CODE");
				String modelName = SystemConfig.getProperty("MODEL.NAME");
				model = new Model(modelParentId,modelCode,modelName,null);
				model.setModelId(modelId);
				model.setModelIsLeaf(0);
				model.setModelLevel(1);
				model.setRowEnable(1);
				model.setCrTime(new Date(System.currentTimeMillis()));
				model.setCrUserId(loginUser.getUserId());
				modelService.persist(model);
			}
			modelMap.addAttribute("modelId", model.getModelId());
			
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/menu/menuIndex.jsp";
	}
	
	@RequestMapping(params = "action=tree")
	public String tree(ModelMap modelMap, Model model, HttpSession session,HttpServletRequest request)
			throws Exception {
		try {
			String context = request.getContextPath(); //session.getServletContext().getContextPath();
			List tree = new ArrayList();
			
			List dTreeList = new ArrayList();
			Model topModel = modelService.get(model.getModelId());
			dTreeList.add(new DTreeBean(topModel.getModelId(),topModel.getModelParentId(), topModel.getModelName(),
					context+"/admin/menu.do?action=list&modelId="+topModel.getModelId(),
					topModel.getModelName(),"treeListFrame"));
			
			List list = modelService.findTree(model.getModelId(),tree);
			for (int i = 0; i < list.size(); i++) {
				Model e = (Model)list.get(i);
				DTreeBean dTree = new DTreeBean(e.getModelId(),
						e.getModelParentId(),
						e.getModelName(),
						context+"/admin/menu.do?action=list&modelId="+e.getModelId(),
						e.getModelName(),"treeListFrame");
				dTreeList.add(dTree);
			}
			modelMap.addAttribute("list", dTreeList);
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/menu/menuLeft.jsp";
	}

	@RequestMapping(params = "action=list")
	public String list(ModelMap modelMap, Menu menu, HttpSession session)
			throws Exception {
		try {
			List list = service.findWithPaging(menu);
			for (int i = 0; i < list.size(); i++) {
				Menu o = (Menu)list.get(i);
				o.setModelName(modelService.get(o.getModelId()).getModelName());
			}
			modelMap.addAttribute("list", list);
			modelMap.addAttribute("command",menu);
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/menu/menuList.jsp";
	}
	
	@RequestMapping(params = "action=new")
	public String neu(ModelMap modelMap, Menu menu, HttpSession session)
			throws Exception {
		try {
			Model e = modelService.get(menu.getModelId());
			if(null != e){
				menu.setModelName(e.getModelName());
				menu.setRowOrder(service.getMaxRowOrder(menu));
			}
			modelMap.addAttribute("command",menu);
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/menu/menuSaveEdit.jsp";
	}
	
	@RequestMapping(params = "action=edit")
	public String edit(ModelMap modelMap, Menu menu, HttpSession session) throws Exception {
		try {
			Menu command = service.get(menu.getMenuId());
			if(null != command){
				Model e = modelService.get(command.getModelId());
				if(null != e){
					command.setModelName(e.getModelName());
				}
				modelMap.addAttribute("command",command);
			} else {
				modelMap.addAttribute("command",menu);
				modelMap.addAttribute("code","missing.current.data");
				modelMap.addAttribute("isError","true");
			}
		} catch (Exception e) {
			logger.error("", e);
			modelMap.addAttribute("code","unknowing.error");
			modelMap.addAttribute("isError","true");
			modelMap.addAttribute("command", menu);
		}
		return "forward:/admin/menu/menuSaveEdit.jsp";
	}
	
	@RequestMapping(params = "action=remove")
	public String remove(ModelMap modelMap, Menu menu, HttpSession session)
			throws Exception {
		modelMap.addAttribute("code", "menu.remove.success");
		Menu m = new Menu();
		m.setModelId(menu.getModelId());
		try {
			Menu command = service.get(menu.getMenuId());
			if(null != command){
				m.setModelId(command.getModelId());
				modelMap.addAttribute("command",m);
				service.remove(menu.getMenuId());
			} else {
				modelMap.addAttribute("command",menu);
				modelMap.addAttribute("code","missing.current.data");
				modelMap.addAttribute("isError","true");
			}
		} catch (Exception e) {
			logger.error("", e);
			modelMap.addAttribute("code", "menu.remove.failed");
			modelMap.addAttribute("isError", "true");
//			throw e;
		}
		return list(modelMap,m,session);
	}
	
	@RequestMapping(params = "action=mutilRemove")
	public String mutilRemove(ModelMap modelMap, Menu menu, HttpSession session)
			throws Exception {
		modelMap.addAttribute("code", "menu.remove.success");
		try {
			service.mutilRemove(menu);
			modelMap.addAttribute("command",menu);
			
		} catch (Exception e) {
			logger.error("", e);
			modelMap.addAttribute("code", "menu.remove.failed");
			modelMap.addAttribute("isError", "true");
//			throw e;
		}
		return list(modelMap,menu,session);
	}
	
	@RequestMapping(params = "action=saveEdit")
	public String saveEdit(ModelMap modelMap,  Menu menu, HttpSession session)
			throws Exception {
		String menuId = menu.getMenuId();
		try {
			User loginUser = (User) session.getAttribute("loginUser");
			
			if (menuId == null || menuId.length() == 0) {
				modelMap.addAttribute("code", "menu.new.success");
				
				menu.setCrUserId(loginUser.getUserId());
				menu.setCrTime(new Date(System.currentTimeMillis()));
				service.save(menu);

				if("saveAndNew".equals(menu.getSaveAndNew())){
					Menu m = new Menu();
					m.setModelId(menu.getModelId());
					return neu(modelMap,m , session);
				} else {
					return edit(modelMap, menu, session);
				}
			} else {
				modelMap.addAttribute("code", "menu.modify.success");
				menu.setUpUserId(loginUser.getUserId());
				menu.setUpTime(new Date(System.currentTimeMillis()));
				service.update(menu);
				if("saveAndNew".equals(menu.getSaveAndNew())){
					Menu m = new Menu();
					m.setModelId(menu.getModelId());
					return neu(modelMap,m , session);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			modelMap.addAttribute("isError", "true");
			if (menuId == null || menuId.length() == 0) {
				modelMap.addAttribute("code", "menu.new.failed");
				modelMap.addAttribute("command", menu);
				return neu(modelMap, menu, session);
			} else {
				modelMap.addAttribute("code", "menu.modify.failed");
				return edit(modelMap, menu, session);
			}
		}
		
		return list(modelMap, menu, session);
	}
}

